package com.xros.demo.gamedataserver.domian.message;

import com.alibaba.fastjson.JSONObject;
import lombok.Data;

import java.nio.charset.StandardCharsets;

/**
 * @Author: mzp
 * @Description: 消息的包装类
 * @Date: 2024/3/26 17:24
 * @Version: 1.0
 */
@Data
public class MessageWrapper {

    /**
     * 魔术值
     */
    private int magicNumber;

    /**
     * 版本号
     */
    private byte version;

    /**
     * 消息类型
     */
    private byte msgType;

    /**
     * 序列化算法类型
     */
    private byte algorithm;

    /**
     * 序列号
     */
    private int sequence;

    /**
     * 消息长度
     */
    private int length;

    /**
     * 消息主体对象
     */
    private CustomerMessage content;


    public boolean setContentByMsgType(byte[] contentBytes) {

        boolean setResult = false;

        try {
            //如果是json序列化方式
            if (algorithm == 0) {
                String jsonStr = new String(contentBytes, StandardCharsets.UTF_8);

                final Class<?> msgClzByType = CustomerMessage.getMsgClzByType(msgType);
                this.content = (CustomerMessage) JSONObject.parseObject(jsonStr, msgClzByType);
                setResult = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return setResult;
    }

}
